<template>
  <a-card :bordered="false" :bodyStyle="{ minHeight: `${layoutContentHeight - pageHeaderHeight - 2}px` }">
    <a-form :form="form">
      <a-card title="平台基础数据接收服务器配置" :bordered="false">
        <a-form-item label="是否开启数据回调">
          <a-switch v-decorator="['callbackOpen', { valuePropName: 'checked' }]"></a-switch>
        </a-form-item>
        <a-form-item label="URL  (填写的URL需要正确响应MOSURL的认证)">
          <a-input
            v-decorator="[
              'callbackUrl',
              {
                rules: [{ required: true, message: '请填写URL' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="Token">
          <a-input
            ref="token"
            disabled
            v-decorator="[
              'token',
              {
                rules: [{ required: true, message: '请获取Token' }]
              }
            ]"
          ></a-input>
          <a-button type="primary" @click="getRandom('token')" style="margin-right:10px;">重新获取</a-button>
          <a-button @click="copy('token')">复制</a-button>
        </a-form-item>
        <a-form-item label="AESKey">
          <a-input
            ref="aesKey"
            disabled
            v-decorator="[
              'aesKey',
              {
                rules: [{ required: true, message: '请获取AesKey' }]
              }
            ]"
          ></a-input>
          <a-button type="primary" @click="getRandom('aesKey')" style="margin-right:10px;">重新获取</a-button>
          <a-button @click="copy('aesKey')">复制</a-button>
        </a-form-item>
      </a-card>
      <!-- <a-divider /> -->
      <a-card title="选择需要接收的数据类型" :bordered="false">
        <a-form-item v-for="item in optionData" :key="item.type" :label="item.typeName">
          <a-checkbox-group
            v-model="chooseData[item.type]"
            :options="item.dataList"
            @change="onCheckChange(item.type, $event)"
          >
          </a-checkbox-group>
        </a-form-item>
        <!-- <a-form-item label="组织模型">
            <a-checkbox v-decorator="['org', { valuePropName: 'checked' }]">组织架构</a-checkbox>
          </a-form-item>
          <a-form-item label="生产资源">
            <a-checkbox-group v-decorator="['sourceGroup']" style="width: 100%;">
              <a-row>
                <a-checkbox value="position">
                  岗位基础数据
                </a-checkbox>
                <a-checkbox value="qualification">
                  资质基础数据
                </a-checkbox>
                <a-checkbox value="staff">
                  人员岗位资质
                </a-checkbox>
                <a-checkbox value="modeling">
                  工厂建模
                </a-checkbox>
                <a-checkbox value="calendar">
                  工厂日历
                </a-checkbox>
                <a-checkbox value="procedure">
                  工序数据
                </a-checkbox>
              </a-row>
            </a-checkbox-group>
          </a-form-item>
          <a-form-item label="产品资料">
            <a-checkbox-group v-decorator="['productGroup']" style="width: 100%;">
              <a-row>
                <a-checkbox value="material">
                  物料基础数据
                </a-checkbox>
                <a-checkbox value="bom">
                  物料BOM
                </a-checkbox>
                <a-checkbox value="bad-code">
                  不良代码
                </a-checkbox>
              </a-row>
            </a-checkbox-group>
          </a-form-item> -->
      </a-card>
      <a-divider />
      <a-form-item v-action:edit :colon="false" label=" ">
        <a-button style="margin-right: 20px" @click="handleSubmit" type="primary">提交</a-button>
        <a-button @click="init">取消</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { layoutMixin } from '@/utils/mixin';
import { getRandomKey, getSyncData, updateSyncData, getBasicList } from '@/api/application';
export default {
  name: 'BaseDataConfig',
  mixins: [layoutMixin],
  components: {},
  mounted() {
    this.init();
  },
  data() {
    return {
      form: this.$form.createForm(this),
      basicOpt: [],
      chooseData: {}
    };
  },
  methods: {
    handleBack() {
      this.$router.back();
    },
    init() {
      getBasicList().then(res => {
        this.basicOpt = res.data;
        getSyncData({ id: this.id }).then(res => {
          if (res.data) {
            this.parseChooseData(res.data.dataType);
            this.$nextTick(() => {
              this.form.setFieldsValue({
                callbackUrl: res.data.callbackUrl,
                token: res.data.token,
                aesKey: res.data.aesKey,
                callbackOpen: res.data.callbackOpen ? true : false
                // org: !!res.data.dataType ? (res.data.dataType.indexOf('org') > -1 ? true : false) : false,
                // sourceGroup: !!res.data.dataType ? this.isInGroup(this.sourceGroupKey, res.data.dataType) : [],
                // productGroup: !!res.data.dataType ? this.isInGroup(this.productGroupKey, res.data.dataType) : []
              });
            });
          }
        });
      });
    },
    isInGroup(keyArr, data) {
      const arr = [];
      keyArr.forEach(d => {
        if (data.indexOf(d) > -1) {
          arr.push(d);
        }
      });
      return arr;
    },
    getRandom(key) {
      getRandomKey().then(res => {
        this.form.setFieldsValue({
          [key]: res.data
        });
        this.$message.success(res.message);
      });
    },
    copy(key) {
      if (typeof navigator.clipboard == 'undefined') {
        const textArea = document.createElement('textarea');
        textArea.value = this.form.getFieldsValue()[key];
        textArea.style.position = 'fixed'; //avoid scrolling to bottom
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
          const successful = document.execCommand('copy');
          const msg = successful ? '已复制进剪贴板' : '复制发生错误';
          this.$message.success(msg);
        } catch (err) {
          this.$message.error('复制发生错误');
        }
        document.body.removeChild(textArea);
        return;
      }
      navigator.clipboard.writeText(this.form.getFieldsValue()[key]).then(() => {
        this.$message.success('已复制进剪贴板');
      });
    },
    handleSubmit() {
      this.form.validateFields((err, value) => {
        console.log(err, value);
        if (err) {
          return;
        }
        const { callbackUrl, token, aesKey, callbackOpen } = value;
        let dataType = [];
        for (const key in this.chooseData) {
          if (this.chooseData.hasOwnProperty(key)) {
            dataType = dataType.concat(this.chooseData[key]);
          }
        }
        updateSyncData({
          id: this.id,
          callbackUrl,
          token,
          aesKey,
          callbackOpen: callbackOpen ? 1 : 0,
          dataType: dataType.join()
        }).then(res => {
          this.$message.success(res.message);
        });
      });
    },
    parseChooseData(dataType) {
      const dataArr = dataType ? dataType.split(',') : [];
      const obj = {};
      this.basicOpt.forEach(d => {
        obj[d.type] = [];
        dataArr.forEach(e => {
          if (
            d.dataList.findIndex(u => {
              return u.dataType === e;
            }) > -1
          ) {
            obj[d.type].push(e);
          }
        });
      });
      this.chooseData = obj;
    },
    onCheckChange(type, checkedValues) {
      this.chooseData[type] = checkedValues;
    }
  },
  computed: {
    id() {
      const id = this.$route.query.id;
      return id ? parseInt(id) : 0;
    },
    // optionsVal() {
    //   let obj = {};
    //   this.basicOpt.forEach(d => {
    //     obj[d.type] = [];
    //     d.dataList.forEach(e => {
    //       if (this.chooseData[d.type].includes(e.dataType)) {
    //         obj[d.type].push(e.dataType);
    //       }
    //     });
    //   });
    //   return obj;
    // },
    optionData() {
      const arr = [];
      this.basicOpt.forEach(d => {
        const obj = {};
        obj.dataList = d.dataList.map(e => {
          return { value: e.dataType, label: e.dataName };
        });
        obj.typeName = d.typeName;
        obj.type = d.type;
        arr.push(obj);
      });
      return arr;
    }
  }
};
</script>

<style scoped></style>
